<?php
namespace app\facility\controller;

use think\Controller;
use app\facility\model\CollectMobileInfo;
use app\index\controller\Builder;
use think\Db;
use think\Cache;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;
use app\facility\Util\CCPHelper;

class Receiver extends Controller
{
    public function get_machine_info($data = "", $id = "", $temp = "")
    {
        // write_log("data:" . $data, 1);
        // write_log("id:" . $id, 1);
    	// $data = "-90|13|48:e2:44:58:87:23|2017-09-15 09:35:29;-93|2|00:0c:e7:74:82:74|2017-09-15 09:35:30";
        // -84|4|ac:18:26:e7:ad:2c|2017-11-22 17:32:50;-48|7|d4:a1:48:85:e7:d2|2017-11-22 17:32:52;-88|12|ac:18:26:e7:ad:2c|2017-11-22 17:32:54;-87|5|ac:18:26:e7:ad:2c|2017-11-22 17:32:58;
    	// $id = "763000"; 
        if ($id == "" || $data == "") {
        	return 'no';
        }
        
        $pid = Db::table('billboard')->where('device_id', $id)->value('id');

        if (!$pid) {
            return "no";
        }

        if ($temp && $temp != "0" && $temp != "-127.00") {
            $temperature = Cache::get("billboard_temp_" . $pid);
            if (!$temperature) {
                //&& $temp != "85.00" && $temp != "0" && $temp != "0.00"
                $sql = "insert into billboard_temp_" . $pid
                    . "(temp,add_time) values('" . $temp . "','" .
                    date('Y-m-d H:i:s') . "')";
                Db::execute($sql);
                Cache::set("billboard_temp_" . $pid, $temp, 60);
            }
        }

        $array = array(
        	'0' => 'rssi',
        	'1' => 'channel',
        	'2' => 'mac',
        	'3' => 'add_time',
        	);
        $data = explode(';', $data);
        foreach ($data as $key => $value) {
            if (!empty($value)) {
            	$data[$key] = explode("|", $value);
                // $data[$key]['pid'] = $pid;
            	// $data[$key][3] = date('Y-m-d H:i:s');
            	foreach ($data[$key] as $k => $v) {
            		if (isset($array[$k])) {
            			$flowData[$key][$array[$k]] = $v;
            		} else {
            			$flowData[$key][$k] = $v;
            		}
            	}
            }
        }
        // dump($flowData);
        foreach ($flowData as $key => $value) {
            $mac_id = Cache::get("mac_" . $value['mac']);
            if (!$mac_id) {
                $vendor_id = Cache::get("vendor_mac_" . substr($value['mac'], 0, 8));
                if (!$vendor_id) {
                    $vendor_id = -1;
                }
                $m = new CollectMobileInfo;
                $m->vendor_id = $vendor_id;
                $m->mac = $value['mac'];
                $m->add_time = $value['add_time'];
                $m->save();
                $mac_id = $m->id;
                Cache::set("mac_" . $value['mac'], $mac_id);
            }
            $sql = "insert into billboard_mac_" . $pid
                . "(mac_id,add_time,channel,rssi,collect_time) values('" . $mac_id . "','" .
                date('Y-m-d H:i:s') . "','" . $value['channel'] . "','" . $value['rssi'] . "','" . $value['add_time'] . "')";
            Db::execute($sql);
            // 保存缓存查询设备连接情况
            $update_bil = Cache::get("update_billboard_" . $pid);
            $img_bil = Cache::get("img_billboard_" . $pid);
            $type = 1;
            $device_type = 1;
            if ($update_bil) {
                $type = $update_bil['type'] == 2 ? 3 : ($update_bil['type'] == 3 ? 3 : 1);
            }
            if ($img_bil) {
                $device_type = ($img_bil['type'] == 2) ? 2 : 1;
            }
            Cache::set("update_billboard_" . $pid, array('time'=>time() + 60 * 5,'type'=>$type,'device_type'=>$device_type));
            // 保存mac轨迹重复率
            $mac_track = Cache::get("billboard_mac_track_" . $pid . "_" . $value['mac']);
            if (!$mac_track) {
                $trackSql = "insert into billboard_mac_track_" . $pid
                . "(mac_id,quantity,add_time,collect_time) values('" . $mac_id . "','1','" . date('Y-m-d H:i:s') . "','" . $value['add_time'] . "')";
                Cache::set("billboard_mac_track_" . $pid . "_" . $value['mac'], $mac_id);
            } else {
                $trackSql = "update billboard_mac_track_" . $pid . " set quantity=quantity+1, collect_time='" . date('Y-m-d H:i:s') . "' where mac_id=" . $mac_id;
            }
            Db::execute($trackSql);

            $outline_mac = Cache::get("billboard_mac_" . $value['mac']);
            if (!$outline_mac) {
                $sql = "insert into billboard_mac_outline_" . $pid
                    . "(mac_id,add_time,collect_time) values('" . $mac_id . "','" .
                    date('Y-m-d H:i:s') . "','" . $value['add_time'] . "')";
                Db::execute($sql);
                Cache::set("billboard_mac_" . $value['mac'], "o", 60 * 30);
            }
        }
        return 'ok';
    }

    public function uploadimg($data = "", $vc_id = "", $order_num = 1, $is_last = 0, $hex_data_count = 1)
    {
        if ($data == "") {
            return "no";
        }
        if ($order_num == 1) {
            Db::execute("delete from vc_img_hex WHERE vc_id='" . $vc_id . "';");
            $deviceInfo = get_device_info($vc_id);
            $sql = "update billboard set latest_img_time='" . date('Y-m-d H:i:s') . "' where id=" . $deviceInfo[0];
            Db::execute($sql);
        }
        $sql = "insert into vc_img_hex(data,vc_id,order_num,add_time,hex_data_count) values('" . $data . "','"
            . $vc_id . "','" . $order_num . "','" . date('Y-m-d H:i:s') . "'," . $hex_data_count . ")";
        Db::execute($sql);
        $sql = "insert into vc_img_hex_log(data,vc_id,order_num,add_time,hex_data_count) values('" . $data . "','"
            . $vc_id . "','" . $order_num . "','" . date('Y-m-d H:i:s') . "'," . $hex_data_count . ")";
        Db::execute($sql);

        // 查询设备容联云账号和广告牌信息
        $Billboard = \think\Loader::model('Billboard');
        $billReturn = $Billboard->getRelationInfo($vc_id);

        if ($is_last == 1) {
            $sql = "SELECT * FROM vc_img_hex WHERE vc_id='" . $vc_id . "' ORDER BY order_num asc;";
            $temp = Db::query($sql);
            $data = "";
            $temp_order_num = "";
            foreach ($temp as $item) {
                if ($temp_order_num != $item["order_num"]) {
                    $data .= $item["data"];
                    $temp_order_num = $item["order_num"];
                }
            }
            //echo $data;
            $imgdata = base64_encode(pack('H*', $data));
            $path1 = "/static/camimg/" . date('Ymd', time()) . "/";
            $new_file = APP_ROOT_PATH . $path1;
            //echo $new_file;
            if (!file_exists($new_file)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $file_name = $vc_id . "_" . time() . ".jpg";
            $new_file = $new_file . $file_name;
            if (file_put_contents($new_file, base64_decode($imgdata))) {
                $deviceInfo = get_device_info($vc_id);
                
                $camera = \think\Loader::model('Camera','logic');
                // oss上传
                $ossReturn = $camera->ossUpload($file_name, $new_file);
                if ($ossReturn) {
                    $sql = "insert into aliyun_oss (name,tab,pid,add_time) values('" . $file_name . "','billboard','" . $deviceInfo[0] . "','" . date('Y-m-d H:i:s') . "')";
                } else {
                    $sql = "insert into aliyun_oss (name,tab,pid,path,add_time) values('" . $file_name . "','billboard','" . $deviceInfo[0] . "','" . $path1 . "','" . date('Y-m-d H:i:s') . "')";
                }
                Db::execute($sql);
                $ossId = Db::table('aliyun_oss')->getLastInsID();
                Db::execute("delete from vc_img_hex WHERE vc_id='" . $vc_id . "';");

                // 发送图片更新消息
                $sendUrl = ['type'=>'300','hex'=>'0','complete'=>'1','pid'=>$billReturn['user_info']['pid'],'msgContent'=>'完成上传'];
                $url = "http://39.108.178.245:55151/PushMsg.php?recevicers=".$billReturn['receiver']."&content=".json_encode($sendUrl);
                $result = https_request($url);

                // 图片比对
                $camera->compare_img($new_file, $ossId, $billReturn['receiver'], $billReturn['user_info']);
                unlink($new_file);
                return "ok";
            } else {
                return "saveimgfail";
            }
        } else {
            $hex = $order_num / $hex_data_count * 100;
            $sendUrl = ['type'=>'300','hex'=>$hex,'complete'=>'0','pid'=>$billReturn['user_info']['pid'],'msgContent'=>'进度条'];
            $url = "http://39.108.178.245:55151/PushMsg.php?recevicers=".$billReturn['receiver']."&content=".json_encode($sendUrl);
            $result = https_request($url);
        }
        return "ok";
    }

    public function get_drainge_info($data = "", $id = "")
    {
        // $data = "-84|4|ac:18:26:e7:ad:2c|2017-11-22 17:32:50;-48|7|d4:a1:48:85:e7:d2|2017-11-22 17:32:52;-88|12|ac:18:26:e7:ad:2c|2017-11-22 17:32:54;-87|5|ac:18:26:e7:ad:2c|2017-11-22 17:32:58";
        // $id = "123456"; 
        if ($id == "" || $data == "") {
            return 'no';
        }
        
        $pid = Db::table('drainage_device')->where('device_id', $id)->value('id');

        if (!$pid) {
            return "no";
        }

        $array = array(
            '0' => 'rssi',
            '1' => 'channel',
            '2' => 'mac',
            '3' => 'add_time',
            );
        $data = explode(';', $data);
        foreach ($data as $key => $value) {
            if (!empty($value)) {
                $data[$key] = explode("|", $value);
                foreach ($data[$key] as $k => $v) {
                    if (isset($array[$k])) {
                        $flowData[$key][$array[$k]] = $v;
                    } else {
                        $flowData[$key][$k] = $v;
                    }
                }
            }
        }

        foreach ($flowData as $key => $value) {
            $mac_id = Cache::get("mac_" . $value['mac']);
            if (!$mac_id) {
                $vendor_id = Cache::get("vendor_mac_" . substr($value['mac'], 0, 8));
                if (!$vendor_id) {
                    $vendor_id = -1;
                }
                $m = new CollectMobileInfo;
                $m->vendor_id = $vendor_id;
                $m->mac = $value['mac'];
                $m->add_time = $value['add_time'];
                $m->save();
                $mac_id = $m->id;
                Cache::set("mac_" . $value['mac'], $mac_id);
            }
            $sql = "insert into drainage_mac_" . $pid
                . "(mac_id,add_time,channel,rssi,collect_time) values('" . $mac_id . "','" .
                date('Y-m-d H:i:s') . "','" . $value['channel'] . "','" . $value['rssi'] . "','" . $value['add_time'] . "')";
            Db::execute($sql);
            // 保存缓存查询设备连接情况
            $update_bil = Cache::get("drainage_device_" . $pid);
            $type = 1;
            if ($update_bil) {
                $type = $update_bil['type'] == 2 ? 3 : ($update_bil['type'] == 3 ? 3 : 1);
            }
            Cache::set("drainage_device_" . $pid, array('time'=>time() + 60 * 5,'type'=>$type));

            $outline_mac = Cache::get("drainage_mac_" . $value['mac']);
            if (!$outline_mac) {
                $sql = "insert into drainage_outline_mac_" . $pid
                    . "(mac_id,add_time,collect_time) values('" . $mac_id . "','" .
                    date('Y-m-d H:i:s') . "','" . $value['add_time'] . "')";
                Db::execute($sql);
                Cache::set("drainage_mac_" . $value['mac'], "o", 60 * 30);
            }
            // dump(Cache::get("drainage_mac_" . $value['mac']));
        }
        return 'ok';
    }




    public function test()
    {
        $path1 = "/static/camimg/" . date('Ymd', time()) . "/";
        $new_file = APP_ROOT_PATH . $path1;
        echo $new_file;
        if (!file_exists($new_file)) {
//检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        echo "000";
    }

    public function test_demo()
    {
        // 保存缓存查询设备连接情况
        $update_bil = Cache::get("update_billboard_15");
        $img_bil = Cache::get("img_billboard_15");
        dump($update_bil);
        dump($img_bil);
        $device_type = 1;
        // $type = $update_bil ? ($update_bil['type'] == 2 ? 3 : 1) : 1;
        if ($img_bil) {
            $device_type = ($img_bil['type'] == 2) ? 2 : 1;
        }
        $type = 1;

        Cache::set("update_billboard_15", array('time'=>time() + 60 * 5,'type'=>$type,'device_type'=>$device_type));
        dump(Cache::get('update_billboard_15'));
    }

    public function test_uploda($id = "4407674")
    {
        $sql = "SELECT `order_num` / `hex_data_count`*100  FROM `vc_img_hex` WHERE `vc_id` ='". $id ."' ORDER BY `order_num`  desc limit 1";
        $hex = Db::query($sql);
        if (!empty($hex)) {
            $hex = $hex[0]["`order_num` / `hex_data_count`*100"];
        } else {
            $hex = 1;
        }
        $complete = 0;

        $where = ['device_id'=>$id,'ub.end_time'=>array('EGT',date('Y-m-d H:i:s',time()))];
        $user_info = Db::table('billboard')->alias('b')
                                    ->where($where)
                                    ->join('user_relation_billboard ub', 'ub.billboard_id = b.id')
                                    ->join('ronglian_account ra', 'ra.user_id = ub.user_id')
                                    ->field('b.id as pid, ra.voipAccount, ra.user_id, b.standard_img_id, b.begin_time, b.end_time, b.is_monitor, b.night_img_id, b.name as bname')
                                    ->find();
        // dump($user_info);
        if ($user_info['user_id'] == 33) {
            $receiver = Db::table('user')->alias('u')->where('u.isDemo', 1)->join('ronglian_account ra', 'ra.user_id = u.id')->column('ra.voipAccount');
            $receiver = implode(',', $receiver);
        } else {
            $receiver = $user_info['voipAccount'];
        }
        dump($receiver);
        // if ($hex % 5 == 0 || $hex == 1) {
        //     $sendUrl = ['type'=>'300','hex'=>$hex,'complete'=>'0','pid'=>$user_info['pid'],'msgContent'=>'进度条'];
        //     $url = "http://39.108.178.245:55151/PushMsg.php?recevicers=".$receiver."&content=".json_encode($sendUrl);
        //     $result = https_request($url);
        //     dump($result);
        //     dump($sendUrl);
        // }
        dump($hex);
        $ossId = 255;
        // $standard_file = APP_ROOT_PATH . $user_info['path'] . $user_info['ossname'];
        $new_file = 'F:/workspace/DataGatherServer/public/static/compare/b2.jpg';
        if ($hex == 1) {
            $camera = \think\Loader::model('Camera','logic');
            $camera->compare_img($new_file, $ossId, $receiver, $user_info);
        }

        // $accessKeyId = "LTAIUUs2Bmew3u62";
        // $accessKeySecret = "rYjZYbiyT1GzNIdwMgULqfIz8C943X";
        // $endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
        // $bucket= "bomeiyi";
        // $object = "12297450_1506474298.jpg";
        // $filePath = APP_ROOT_PATH . "/static/camimg/20170927/12297450_1506474298.jpg";
        // try {
        //     $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //     $ossClient->uploadFile($bucket, $object, $filePath);
        // } catch (OssException $e) {
        //     print $e->getMessage();
        // }
    }

    








}
